package com.xgp.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.xgp.order.bean.Order;
import com.xgp.order.feign.ProductFeignClient;
import com.xgp.order.service.OrderService;
import com.xgp.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient; // 服务发现

    @Autowired
    RestTemplate restTemplate; // 远程调用

    @Autowired
    LoadBalancerClient loadBalancerClient; // 负载均衡

    @Autowired
    ProductFeignClient productFeignClient;

// 定义资源
    @SentinelResource(value = "createOrder",blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long productId, Long userId) {
        // 远程调用
//        Product product = getProductFromRemoteWithLoadBalanceAnnotation(productId);
        // 使用feign远程调用
        Product product = productFeignClient.getProductById(productId);

        Order order = new Order();
        order.setId(1L);
        // TODO 远程查询总金额
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("xgp");
        order.setAddress("赣州市");
        // TODO 远程查询商品列表
        order.setProductList(Arrays.asList(product));

        return order;
    }

//    兜底回调
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickName("未知用户");
        order.setAddress("异常信息"+e.getClass());
        return order;
    }

    private Product getProductFromRemote(Long productId) {
        //1、获取到商品服务所在的所有机器ip+port
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        log.info("远程请求:{}",url);
        //2、给远程发送请求（建议进行全局配置）
//        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.getForObject(url, Product.class);
    }

//    增加了负载均衡
    private Product getProductFromRemoteWithLoadBalance(Long productId) {
        //1、获取到商品服务所在的所有机器ip+port
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/product/" + productId;
        log.info("远程请求:{}",url);
        return restTemplate.getForObject(url, Product.class);
    }

    //    基于注解的负载均衡
    @LoadBalanced
    private Product getProductFromRemoteWithLoadBalanceAnnotation(Long productId) {
        //1、动态确定商品服务所在的所有机器ip+port
        String url = "http://service-product/product/" + productId;
        return restTemplate.getForObject(url, Product.class);
    }
}
